<template>
  <div class="user">
    <!-- 搜索框 -->
    <div class="search">
      <div class="input">
        <el-input v-model="roleName" clearable placeholder="请输入角色名" @keyup.enter.native="searchNums" />
      </div>
      <el-button type="primary" icon="el-icon-search" @click="searchNum"/>
      <!-- 增加按钮 -->
      <div class="add">
        <el-button type="text" @click="showRolePopUp">
        <i class="el-icon-circle-plus"/></el-button>
        <el-dialog :visible.sync="dialogFormVisible" title="增加新角色">
          <el-form ref="role" :model="role" :rules="roleRules">
            <el-form-item :label-width="formLabelWidth" label="角色名：" prop="name">
              <el-input v-model="role.name" clearable/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="角色说明：" prop="remark">
              <el-input v-model="role.remark" clearable/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click.stop="addRole()">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>

    <!-- 中间表格 -->
    <div class="table">
      <el-table :data="tableData" border highlight-current-row>
        <el-table-column align="center" fixed prop="date" label="序号">
          <template slot-scope="scope">
            <span>{{ (page-1 )* pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="角色名">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="province" label="说明">
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | fmtdate }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" min-width="150">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="text" style="margin-right:20px;" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-dialog :title="'修改【'+ title +'】角色'" :visible.sync="dialogEditorVisible" :modal="false">
              <el-form ref="editor" :model="editor" :rules="editorRules">
                <el-form-item :label-width="formLabelWidth" label="角色名：" prop="name">
                  <el-input v-model="editor.name" :placeholder="editor.name" clearable/>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="角色说明：" prop="remark">
                  <el-input v-model="editor.remark" :placeholder="editor.remark" clearable/>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditorVisible = false">取 消</el-button>
                <el-button type="primary" @click.stop="toEditor()">确 定</el-button>
              </div>
            </el-dialog>
            <!-- 删除按钮 -->
            <el-button
              type="text"
              style="margin-right:10px;"
              size="small"
              @click.native.prevent="deleteRow(scope.$index, tableData)">删除</el-button>
            <!-- 授权按钮 -->
            <el-button type="text" size="small" @click="accredit(scope.$index, scope.row)">授权</el-button>
            <el-dialog :title="'对【'+ title +'】角色授权'" :visible.sync="dialogAuthVisible" :modal="false">
              <template slot-scope="scope">
                <div v-for="(items,index) in internationalAuthTree" :key="index" style="text-align: left;">
                  <!-- 一级菜单 -->
                  <p style="margin-left:120px;">
                    {{ items.title }}
                  </p>
                  <!-- 没有二级菜单的情况 -->
                  <li v-if="!items.children" style="margin-left:200px;">
                    <template>
                      <el-checkbox-group v-model="authBtnList">
                        <el-checkbox
                          v-for="(v, index) in items.data.buttonList"
                          :label="v.id +'+' +v.menuId"
                          :key="index"
                          size="small"
                          @change="getId">{{ v.title }}
                        </el-checkbox>
                      </el-checkbox-group>
                    </template>
                  </li>

                  <!-- 二级菜单 -->
                  <div v-for="(item, index) in items.children" :key="index">
                    <p style="margin-left:160px;">
                      {{ item.title }}
                    </p>
                    <!-- 授权多选框 -->
                    <li style="margin-left:200px;">
                      <template>
                        <el-checkbox-group v-model="authBtnList">
                          <el-checkbox
                            v-for="(v, index) in item.data.buttonList"
                            :label="v.id +'+' +v.menuId"
                            :key="index"
                            size="small"
                            @change="getId">{{ v.name }}
                          </el-checkbox>
                        </el-checkbox-group>
                      </template>
                    </li>
                  </div>

                </div>
              </template>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAuthVisible = false">取 消</el-button>
                <el-button type="primary" @click.stop="Auth()">确 定</el-button>
              </div>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 页码 -->
    <div class="pages">
      <template>
        <div class="block">
          <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"/>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import {
  RoleAddFunC,
  RoleChangeFunC,
  RoleDelIdFunC,
  RoleGetBtnTreeFunC,
  RoleGetBtnFunC,
  RoleAccreditFunC,
  RolePageFunC
} from '../../api/role.js';
import {
  MessageBox
} from 'element-ui';
import { translateMenuTree } from '@/utils/index';

export default {
  name: 'Role',
  data() {
    return {
      dialogFormVisible: false, // 增加新角色弹窗默认不显示
      dialogEditorVisible: false, // 编辑弹窗默认不显示
      dialogAuthVisible: false, // 授权弹窗默认不显示
      total: 0, // 数据总条数
      tableData: [], // 数据列表
      page: 1, // 当前页数
      pageSize: 8, // 当页数据条数
      role: { // 保存增加角色的数据
        name: '',
        remark: ''
      },
      roleRules: { // 验证规则
        name: [{
          required: true,
          trigger: 'blur'
        }],
        remark: [{
          required: true,
          trigger: 'blur'
        }]
      },
      editor: { // 保存编辑的数据
        id: '',
        name: '',
        remark: ''
      },
      editorRules: { // 验证规则
        name: [{
          required: true,
          trigger: 'blur'
        }],
        remark: [{
          required: true,
          trigger: 'blur'
        }]
      },
      authData: '', // 保存授权弹窗的数据
      title: '', // 保存弹窗的title
      formLabelWidth: '100px',
      roleName: '', // 保存搜索的角色名
      defaultProps: { // 树形控件配置
        children: 'children',
        label: 'title',
        value: 'id'
      },
      authTreeData: '', // 授权弹窗数据
      authBtnList: [], // 储存多选框选中的授权按钮id和菜单id
      roleId: '', // 角色Id
      buttonsList: '' // 授权id和菜单id集合
    };
  },

  computed: {
    internationalAuthTree() {
      return translateMenuTree(this.authTreeData, this.$t.bind(this));
    }
  },

  created() {
    this.init(); // 初始化
  },
  methods: {
    // 初始化
    init() {
      this.tableData = [];
      RolePageFunC(this.page, this.pageSize).then(result => {
        this.tableData = result.data.rows;
        this.total = result.data.total;
      });
    },

    // 点击回车键发起搜索
    searchNums() {
      this.page = 1;
      this.tableData = [];
      this.total = 0;
      RolePageFunC(this.page, this.pageSize, this.roleName).then(result => {
        this.tableData = result.data.rows;
        this.total = result.data.total;
      });
    },

    // 点击按钮发起搜索
    searchNum() {
      this.page = 1;
      this.tableData = [];
      this.total = 0;
      RolePageFunC(this.page, this.pageSize, this.roleName).then(result => {
        this.tableData = result.data.rows;
        this.total = result.data.total;
      });
    },

    // 切换页码
    handleCurrentChange(val) {
      this.page = val;
      this.init();
    },

    /** ******************** 新增 *******************/
    // 点击增加按钮 出现弹窗
    showRolePopUp() {
      this.dialogFormVisible = true;
      this.role = {
        name: '',
        remark: ''
      };
      this.$nextTick(function() {
        this.$refs.role.clearValidate(); // 移除校验结果
      });
    },

    // 点击增加角色弹窗 确定按钮
    addRole() {
      if (this.role.name == '' || this.role.remark == '') {
        this.$message({
          message: '请认真填写每一项',
          type: 'error'
        });
      } else {
        RoleAddFunC(this.role.name, this.role.remark).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '增加成功',
              type: 'success'
            });
            this.dialogFormVisible = false;
            this.init();
          } else {
            this.$message({
              message: '增加失败',
              type: 'error'
            });
          }
        });
      }
    },

    /** ******************** 编辑 *******************/
    // 点击编辑按钮 弹窗出现
    handleEdit(index, row) {
      this.editor.id = row.id;
      this.editor.name = row.name;
      this.editor.remark = row.remark;
      this.title = row.name;
      this.dialogEditorVisible = true;
      this.$nextTick(function() {
        this.$refs.editor.clearValidate(); // 移除校验结果
      });
    },

    // 点击编辑弹窗 确定按钮
    toEditor() {
      RoleChangeFunC(this.editor.id, this.editor.name, this.editor.remark).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.dialogEditorVisible = false;
          this.init();
        } else {
          this.$message({
            message: '修改失败',
            type: 'warning'
          });
        }
      });
    },

    /** ******************** 删除 *******************/
    // 点击删除按钮
    deleteRow(index, rows) {
      const id = rows[index].id;
      MessageBox.confirm(
        '确定删除吗？', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        RoleDelIdFunC(id).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            rows.splice(index, 1);
            this.page = 1;
            this.init();
          } else {
            this.$message({
              message: '删除失败',
              type: 'warning'
            });
          }
        });
      });
    },

    /** ******************** 授权 *******************/
    // 点击授权 出现弹窗
    accredit(index, row) {
      this.authData = row;
      this.title = row.name;
      this.roleId = row.id;
      this.dialogAuthVisible = true;
      this.authBtnList = [];

      // 树结构获取当前用户的操作按钮
      RoleGetBtnTreeFunC().then((res) => {
        this.authTreeData = res.data;
      });

      // 获取角色的操作按钮
      RoleGetBtnFunC(this.roleId).then((res) => {
        const item = res.data;
        // 将id和menuId拼接成字符串增加到数组中，达到多选框默认选中效果
        item.map(v => {
          v = v.id + '+' + v.menuId;
          this.authBtnList.push(v);
        });
      });
    },

    // 获取授权id 将字符串转成对象后添加到数组里传给后端
    getId() {
      const items = this.authBtnList;
      this.buttonsList = items.map(v => {
        v = v.split('+');
        return {
          id: Number(v[0]),
          menuId: Number(v[1])
        };
      });
    },

    // 点击授权弹窗确定按钮
    Auth() {
      RoleAccreditFunC(this.buttonsList, this.roleId).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '授权成功',
            type: 'success'
          });
          this.dialogAuthVisible = false;
          this.init();
        } else {
          this.$message({
            message: '授权失败',
            type: 'warning'
          });
        }
      });
    }
  }
};

</script>
<style lang="scss" scoped>
  .user {
    position: relative;
    height: calc(100vh - 50px);
    padding: 20px;
    margin: 0 100px;
  }

  /*搜索框*/
  .search {
    height: 40px;
    padding: 50px 0;

    .input {
      width: 240px;
      margin-right: 5px;
      float: left;
    }

    .add {
      margin-right: 172px;
      float: right;

      /* 放大添加图标 */
      .el-icon-circle-plus {
        transform: scale(2);
      }
    }
  }

  /*中间列表*/
  .table {
    max-height: 627px;
    margin-bottom: 50px;
  }

  /*分页*/
  .pages {
    float: right;
  }

</style>
